menuList[6].onclick();
// 获取数据并渲染
current=1;
pageSize=10;
let result;

async function fun(flagOptions){
    let checkAll = document.querySelector("#checkAll");
    checkAll.checked = false;
    dels=[];
    result = await getData(current,pageSize);
    counts = result.data.totalCounts;
    console.log(counts);
    pages = result.data.totalPage;
    pageFun({
        current:current,
        pages:pages,
        counts:counts,
        flagOptions:flagOptions,
        pageSize:pageSize
    })
}
fun(0);
function getData(current,pageSize){
    return new Promise((resolve, reject) => {
        axios({
            url:'/admin/conservator/findUsersByClass',
            method:'GET',
            params:{
                page:current,
                size:pageSize
                }
            })
            .then(data => {
                decorateFun(data)
                console.log(data.data);
                resolve(data.data);
            })
            .catch(err => {
                console.log(err);
            })
    });
   
}

// 选择出生年月日
var selYear = window.document.getElementById("selYear");
var selMonth = window.document.getElementById("selMonth");
var selDay = window.document.getElementById("selDay");
// 新建一个DateSelector类的实例，将三个select对象传进去
new DateSelector(selYear, selMonth, selDay, 1995, 1, 17);

// 失去焦点判断
function userOnblurFun(e){
    e=e || window.event;
    var target=e.target || e.srcElement;
    let name = target.getAttribute("name");
    console.log(name);
    if(name == "email"){
        if(!isEmail(target.value)){
            // explain({
            //     code:3,
            //     msg:"请见检查邮箱是否正确",
            //     time:3000
            // })
            return false;  
        }
    }else if(name=="telephone"){
        if(!isTelCode(target.value)){
            explain({
                code:3,
                msg:"请见检查邮箱是否正确",
                time:3000
            })
            return false;  
        }
    }

}

// 添加管理员表单
function openAddUserFun(){
    console.log("aa");
    let addUserWindow = cl("addUserWindow");
    let covers = document.getElementsByClassName("covers")[0];
    let addUserTitle = document.getElementsByClassName("addUserTitle")[0];
    let addUserFrom = document.getElementsByClassName("addUserFrom")[0];
    let submitBtn = document.getElementsByClassName("submitBtn")[0];
    submitBtn.setAttribute("onclick","submitAddUserFun()")
    addUserFrom.reset();
    addUserTitle.innerHTML = "添加管理员"
    covers.style.display = "block";
    addUserWindow.style.display = "block";
}
// 提交添加管理员表单
function submitAddUserFun (){
    let addUserFrom = cl("addUserFrom");
    let formMsg = serialize(addUserFrom);
    console.log(formMsg);
    console.warn(email.value);
    if(formMsg.email.length==0||formMsg.password.length==0||formMsg.sex.length==0||formMsg.telephone.length==0||formMsg.nickname.length==0){
        explain({
            code:3,
            msg:"请见检查信息是否填写完整",
            time:3000
        })
    }else{
        axios({
            url:'/admin/users/addAUser',
            method:'POST',
            params:{
                email: email.value,
                password:formMsg.password[0],
                birth:selYear.value+"-"+ selMonth.value + "-" + selDay.value ,
                sex:formMsg.sex[0]==0?"男":"女",
                telephone:formMsg.telephone[0],
                nickname:formMsg.nickname[0],
                flag:2,
                }
            })
            .then(data => {
                console.log(data);
                if(data.data.code==20000){
                    closeUSerFun();
                    fun(0);
                    explain({
                        code:1,
                        msg:"添加成功",
                        time:3000
                    })
                }else{
                    explain({
                        code:2,
                        msg:data.data.data,
                        time:3000
                    })
                }
            })
            .catch(err => {
                console.log(err);
            })
    }
}

// 批量删除
function openDeleteUsersFun(){
    console.log(dels);
    if(dels.length==0){
        explain({
            code:3,
            msg:"请选择需要删除的管理员",
            time:3000
        })
    }else{
        pointFun({
            code:1,
            msg:"是否确认删除选中的管理员"
        })
    }
}
function deleteUsersFun(){
    axios({
        url:'/admin/users/deleteUsers',
        method:'DELETE',
        params:{
            ids:dels
        }
    })
    .then(data => {
        console.log(data);
        if(data.data.code==20000){
            closeUSerFun();
            fun(0);
            explain({
                code:1,
                msg:"删除成功",
                time:3000
            })
        }
    })
    .catch(err => {
        console.log(err);
    })
}
// 删除单个管理员
let userid;
function openDeleteUserFun(e){
    e=e || window.event;
    var target=e.target || e.srcElement;
    userid=target.getAttribute('name');
    pointFun({
        code:2,
        msg:"是否删除该管理员"
    })
    console.warn(target.getAttribute('name'));
}
function deleteUserFun(){
    axios({
        url:'/admin/users/deleteAUser',
        method:'DELETE',
        params:{
            userId:userid
        }
    })
    .then(data => {
        console.log(data);
        if(data.data.code==20000){
            closeUSerFun();
            fun(0);
            explain({
                code:1,
                msg:"删除成功",
                time:3000
            })
        }
    })
    .catch(err => {
        console.log(err);
    })
}
// 搜索通过管理员名
let searchInput = cl("searchInput");
function searchByUsername(){
    console.log(searchInput.value);
    console.log(current);
    console.log(pageSize);
    axios({
        url: '/admin/users/selectUsers',
        method: 'GET',
        params:{
            nickname : searchInput.value,
            page: current,
            size: pageSize
            }
        })
        .then(data => {
            if(data.data.code==20001){
                explain({
                    code:2,
                    msg:"抱歉未找到",
                    time:3000
                })
            }else{
                result = data.data.data;
                counts = result.totalCounts;
                decorateFun(data)
                pageFun({
                    current:result.page,
                    pages:result.totalPage,
                    counts:result.users.length
                })
            }
        })
        .catch(err => {
            console.log(err);
        })
}

// 渲染页面
function decorateFun(data){
    let tbodyMenu = cl("tbodyMenu");
    let dataNums = cl("dataNums");
    let pageMessage = cl("pageMessage");
    let end;
    if(current==1){
        end=data.data.data.users.length;
    }else{
        end =parseInt(current-1)*parseInt(data.data.data.size)+parseInt(data.data.data.users.length);
    }
    dataNums.innerHTML = data.data.data.users.length;
    pageMessage.innerHTML = `第${(current-1)*data.data.data.size+1}到${end}条记录，共${data.data.data.totalCounts}条`;
    tbodyMenu.innerHTML ="";
    let i=0;
    for(let key of data.data.data.users){
        tbodyMenu.innerHTML += `
        <tr>
            <td><input type="checkbox" class="checkbox" name="${key.userId}" onclick="checkboxFun()" target="${i}"  ></td>
            <td class="userName" name="${key.userId}" onclick="checkUserInfo()">${key.nickname==null ? "(未设置)" : key.nickname}</td>
            <td><img class="headimgSmall" id="${key.userId}" src="${key.img}" onclick="openImgWin()" alt="点击放大"></td>
            <td>${key.email}</td>
            <td>${key.telephone==null ? "(未设置)": key.telephone}</td>
            <td>${key.flag==2?"管理员":"管理员"}</td>
            <td>${key.birth==null?'未设置':key.birth}</td>
            <td>
            <button class="btn editBtn"><i name="${key.userId}" onclick="openChageUserInfoFun()" class="iconfont bianji"></i></button>
            <button class="btn delBtn"><i name="${key.userId}" onclick="openDeleteUserFun()" class="iconfont shanchu"></i></button>
            </td>
        </tr>
            `
            i++
        }
}
// 输入框回车事件

function inputEnterFun(){
    console.log("a");
    if(event.keyCode == 13){
        searchByUsername()
    }
}

// 页面刷新
function reloadFun(){
    location.reload();
}

// 选择每页展示数量
function chooseSizeFun(){
    let selectNums = document.getElementById("selectNums");
    console.log(selectNums.children[1]);
    console.warn(selectNums.value);
    current = 1;
    pageSize =selectNums.value;
    fun(1);
    for(let i=0;i<selectNums.children.length;i++) {
        if(selectNums.children.length[i]==selectNums.value){
            selectNums.children.length[i].select="select";
        }
    }
}

// 通过id查询管理员信息
function getDataById(){
    return new Promise((resolve, reject) => {
        axios({
            url:'/admin/users/findById',
            method:'GET',
            params:{
               userId:userid
                }
            })
            .then(data => {
                if(data.data.code==20000){
                    resolve(data.data);
                }
            })
            .catch(err => {
                console.log(err);
            })
    });
}

// 编辑管理员信息
async function openChageUserInfoFun(e){
    e=e || window.event;
    var target=e.target || e.srcElement;
    userid = target.getAttribute("name");
    let addUserWindow = cl("addUserWindow");
    let covers = document.getElementsByClassName("covers")[0];
    let addUserTitle = document.getElementsByClassName("addUserTitle")[0];
    let addUserFrom = document.getElementsByClassName("addUserFrom")[0];
    let submitBtn = document.getElementsByClassName("submitBtn")[0];
    let male = document.getElementById("male");
    let female = document.getElementById("female");
    let flag0 = document.getElementById("flag0");
    let flag1 = document.getElementById("flag1");
    addUserFrom.reset();
    addUserTitle.innerHTML = "编辑管理员信息"
    submitBtn.setAttribute("onclick","submitChangeUserFun()")
    covers.style.display = "block";
    addUserWindow.style.display = "block";
    let userData = await getDataById();
    console.warn(userData);

    email.value=userData.data.email;
    password.value=userData.data.password;
    telephone.value=userData.data.telephone;
    nickname.value=userData.data.nickname;
    console.log(userData.data.sex=='男');
    console.log(userData.data.sex=='女');
    if(userData.data.sex=='男'){
        male.setAttribute('checked','checked')
        female.removeAttribute('checked')
    }else{
        female.setAttribute('checked','checked')
        male.removeAttribute('checked')
    }
   
}
// 查看管理员信息
async function checkUserInfo(e){
    e=e || window.event;
    var target=e.target || e.srcElement;
    userid = target.getAttribute("name");
    let userData = await getDataById();
    let userInfoWindow = cl("userInfoWindow");
    let userInfoMsg = cl("userInfoMsg");
    let covers = cl("covers");
    console.log(userData);
    userInfoMsg.innerHTML="";
    userInfoMsg.innerHTML +=`
    <img src="${userData.data.img==null ? '未设置' : userData.data.img}" alt="">
    <div>
        <span>管理员名：</span>
        <span>${userData.data.nickname==null?'':userData.data.nickname}</span>
    </div>
    <div>
        <span>性别：</span>
        <span>${userData.data.sex}</span>
    </div>
    <div>
        <span>电话：</span>
        <span>${userData.data.telephone==null?'未设置':userData.data.telephone}</span>
    </div>
    <div>
        <span>邮箱：</span>
        <span>${userData.data.email==null?'未设置':userData.data.email}</span>
    </div>
    <div>
        <span>出生日期：</span>
        <span>${userData.data.birth==null?'未设置':userData.data.birth}</span>
    </div>
    <div>
        <span>状态：</span>
        <span>${userData.data.flag==2?'管理员':'商家'}</span>
    </div>
    
    
    `
    userInfoWindow.style.display ='block';
    covers.style.display ='block';
}
// 提交编辑管理员表单
function submitChangeUserFun (){
    let addUserFrom = cl("addUserFrom");
    let formMsg = serialize(addUserFrom);
    console.log(formMsg);
    console.warn(email.value);
    if(formMsg.email.length==0||formMsg.password.length==0||formMsg.sex.length==0||formMsg.telephone.length==0||formMsg.nickname.length==0){
        explain({
            code:3,
            msg:"请见检查信息是否填写完整",
            time:3000
        })
    }else{
        axios({
            url:'/admin/users/updateAVip',
            method:'POST',
            params:{
                email: email.value,
                password:formMsg.password[0],
                birth:selYear.value+"-"+ selMonth.value + "-" + selDay.value ,
                sex:formMsg.sex[0]==0?"男":"女",
                telephone:formMsg.telephone[0],
                nickname:formMsg.nickname[0],
                flag:formMsg.flag[0],
                userId:userid
                }
            })
            .then(data => {
                console.log(data);
                if(data.data.code==20000){
                    closeUSerFun();
                    fun(0);
                    explain({
                        code:1,
                        msg:"修改成功",
                        time:3000
                    })
                }else{
                    explain({
                        code:2,
                        msg:data.data.data,
                        time:3000
                    })
                }
            })
            .catch(err => {
                console.log(err);
            })
    }
}

// 头像的操作

// 预览头像
function fileFun(){
    let headimgBig = cl("headimgBig");
    let file = cl("file");
    let imgFile = file.files[0];
    let imgSrc = window.URL.createObjectURL(imgFile);
    headimgBig.setAttribute('src', imgSrc);
}
// 展示放大图像
function openImgWin(e){
    let headimgBig = cl("headimgBig");
    let changeImgWin = cl("changeImgWin");
    let covers = document.getElementsByClassName("covers")[0];
    e=e || window.event;
    var target=e.target || e.srcElement;
    let src = target.getAttribute("src");
    userid = target.getAttribute("id");
    changeImgWin.style.display ='block'
    covers.style.display ='block'
    headimgBig.src = src;
}
// 修改头像
function submitChangeImgFun(){
    console.log(userid);
    let file = cl("file");
    
    var formData = new FormData()
    formData.append('multipartFile',file.files[0]);
    axios({
        url: `/admin/users/updateAVipImg?userId=${userid}`,
        data: formData,
        method: 'put'
    }).then((data) => {
        console.log(data)
        if(data.data.data.code==20000){
            fun();
            explain({
                code:1,
                msg:"修改成功",
                time:3000
            })
            closeUSerFun()
        }
    }).catch((err) => {
        console.log(err)
    })
}

// 关闭的操作
function closeUSerFun(){
    let userInfoWindow =cl("userInfoWindow");
    let covers = cl("covers");
    let changeImgWin = cl("changeImgWin");
    var addUserWindow = cl("addUserWindow");
    userInfoWindow.style.display = 'none';
    covers.style.display = 'none';
    changeImgWin.style.display = 'none';
    addUserWindow.style.display = 'none';
}